<template>
  <el-container class="coupon-edit">
    <el-main>
      <el-form :model="form.model" :rules="form.rules" ref="formRef" label-width="110px">
        <el-form-item label="券名称" prop="name">
          <el-input v-model="form.model.name" placeholder="例如：国庆优惠券" />
        </el-form-item>
        <el-form-item label="名称备注" prop="description">
          <el-input v-model="form.model.description" placeholder="请输入备注" />
        </el-form-item>
        <el-form-item label="券类型" prop="type">
          <el-radio-group v-model="form.model.type" :disabled="props.modal.params.type == 'edit'">
            <el-radio label="reduce">满减券</el-radio>
            <el-radio label="discount">折扣券</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item class="el-form-item--label-right">
          <el-form-item class="el-form-item__label-auto" label="消费满" prop="enough">
            <div class="sa-w-120">
              <el-input
                type="number"
                v-model="form.model.enough"
                :min="0"
                :disabled="props.modal.params.type == 'edit'"
              >
                <template #append>元</template>
              </el-input>
            </div>
          </el-form-item>
          <el-form-item
            v-if="form.model.type == 'reduce'"
            class="el-form-item__label-auto is-no-asterisk sa-m-l-16"
            label="立减"
            prop="amount"
          >
            <div class="sa-w-113">
              <el-input
                type="number"
                v-model="form.model.amount"
                :min="0"
                :disabled="props.modal.params.type == 'edit'"
              >
                <template #append>元</template>
              </el-input>
            </div>
          </el-form-item>
          <el-form-item
            v-if="form.model.type == 'discount'"
            class="el-form-item__label-auto is-no-asterisk sa-m-l-16"
            label="打"
            prop="amount"
          >
            <div class="sa-w-113">
              <el-input
                type="number"
                v-model="form.model.amount"
                :min="0"
                :max="10"
                :disabled="props.modal.params.type == 'edit'"
              >
                <template #append>折</template>
              </el-input>
            </div>
          </el-form-item>
        </el-form-item>
        <el-form-item v-if="form.model.type == 'discount'" class="el-form-item--label-right">
          <el-form-item class="el-form-item__label-auto" label="最多优惠" prop="max_amount">
            <div class="enough-input">
              <el-input
                type="number"
                v-model="form.model.max_amount"
                class="sa-w-120"
                :min="0"
                :disabled="props.modal.params.type == 'edit'"
              >
                <template #append>元</template>
              </el-input>
            </div>
          </el-form-item>
        </el-form-item>
        <el-form-item label="发券总量" prop="stock">
          <el-input type="number" v-model="form.model.stock" class="sa-w-120" :min="0">
            <template #append>张</template>
          </el-input>
        </el-form-item>
        <el-form-item label="每人限领次数">
          <el-input type="number" v-model="form.model.limit_num" class="sa-w-120" :min="0">
            <template #append>张</template>
          </el-input>
        </el-form-item>
        <el-form-item label="领券时间" prop="get_time" class="get-time">
          <el-date-picker
            v-model="form.model.get_time"
            type="datetimerange"
            value-format="YYYY-MM-DD HH:mm:ss"
            format="YYYY-MM-DD HH:mm:ss"
            :default-time="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 2, 1, 23, 59, 59)]"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            prefix-icon="Calendar"
            :editable="false"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="券有效期" prop="use_time_type">
          <el-radio-group v-model="form.model.use_time_type">
            <el-radio label="days">相对天数</el-radio>
            <el-radio label="range">固定区间</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item class="el-form-item--label-right">
          <template v-if="form.model.use_time_type == 'days'">
            <el-form-item
              class="el-form-item__label-auto is-no-asterisk"
              label="领券"
              prop="start_days"
            >
              <div class="sa-w-120">
                <el-input type="number" v-model="form.model.start_days" :min="0">
                  <template #append>天</template>
                </el-input>
              </div>
            </el-form-item>
            <el-form-item
              class="el-form-item__label-auto is-no-asterisk sa-m-l-16"
              label="后生效，有效期"
              prop="days"
            >
              <div class="sa-w-120">
                <el-input type="number" v-model="form.model.days" :min="0">
                  <template #append>天</template>
                </el-input>
              </div>
            </el-form-item>
          </template>
          <el-form-item
            v-if="form.model.use_time_type == 'range'"
            class="el-form-item__label-auto is-no-asterisk"
            label="固定时间"
            prop="useTime"
          >
            <el-date-picker
              v-model="form.model.use_time"
              type="datetimerange"
              value-format="YYYY-MM-DD HH:mm:ss"
              format="YYYY-MM-DD HH:mm:ss"
              :default-time="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 2, 1, 23, 59, 59)]"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              prefix-icon="Calendar"
              :editable="false"
            ></el-date-picker>
          </el-form-item>
        </el-form-item>
        <el-form-item label="优惠叠加">
          <div>
            <div class="sa-flex">
              <el-switch
                v-model="form.model.is_double_discount"
                :active-value="1"
                :inactive-value="0"
                class="sa-m-r-8"
              />
              <div v-if="form.model.is_double_discount == '1'" class="openswitch"> 开启 </div>
              <div v-if="form.model.is_double_discount == '0'">关闭</div>
            </div>
            <div class="warning-title"> 开启优惠叠加，优惠券将可以和活动一起使用 </div>
          </div>
        </el-form-item>
        <el-form-item label="券状态" prop="status">
          <div>
            <el-radio-group v-model="form.model.status">
              <el-radio label="normal">公开发放</el-radio>
              <el-radio label="hidden">后台发放</el-radio>
              <el-radio label="disabled">禁止使用</el-radio>
            </el-radio-group>
            <div class="warning-title">
              后台发放状态改为别的状态，将导致满赠活动无法赠送该优惠券
            </div>
          </div>
        </el-form-item>
        <el-form-item label="可用范围" prop="use_scope">
          <div>
            <el-radio-group v-model="form.model.use_scope" @change="changeUseScope">
              <el-radio label="all_use">全场通用</el-radio>
              <el-radio label="goods">指定商品可用</el-radio>
              <el-radio label="disabled_goods">指定商品不可用</el-radio>
              <el-radio label="category">指定分类可用</el-radio>
            </el-radio-group>
            <div v-if="form.model.use_scope == 'goods' || form.model.use_scope == 'disabled_goods'">
              <el-button class="is-link sa-m-b-8" type="primary" @click="selectGoods"
                >选择商品</el-button
              >
              <div class="sa-template-wrap" v-if="form.model.items_value.length > 0">
                <div class="title sa-flex">
                  <div class="key">商品信息</div>
                  <div class="oper">操作</div>
                </div>
                <div>
                  <div
                    class="item"
                    v-for="(element, index) in form.model.items_value"
                    :key="element"
                  >
                    <el-form-item class="key">
                      <sa-image :url="element.image" size="40"></sa-image>
                      <div class="goods sa-flex-1 sa-table-line-1 sa-m-l-12">
                        <div class="goods-title sa-m-b-6">
                          {{ element.title }}
                        </div>
                      </div>
                    </el-form-item>
                    <el-form-item class="oper">
                      <el-button class="is-link" type="danger" @click="deleteItems(index)">
                        移除
                      </el-button>
                    </el-form-item>
                  </div>
                </div>
              </div>
            </div>
            <div v-if="form.model.use_scope == 'category'">
              <el-button class="is-link sa-m-b-8" type="primary" @click="selectCategory"
                >选择分类</el-button
              >
              <div class="sa-template-wrap" v-if="form.model.items_value.length > 0">
                <div class="title sa-flex">
                  <div class="key">分类信息</div>
                  <div class="oper">操作</div>
                </div>
                <div>
                  <div
                    class="item"
                    v-for="(element, index) in form.model.items_value"
                    :key="element"
                  >
                    <el-form-item class="key">
                      <div class="goods-title sa-m-b-6">{{ element.name }}</div>
                    </el-form-item>
                    <el-form-item class="oper">
                      <el-button class="is-link" type="danger" @click="deleteItems(index)">
                        移除
                      </el-button>
                    </el-form-item>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </el-form-item>
      </el-form>
    </el-main>
    <el-footer class="sa-footer--submit">
      <el-button
        v-if="modal.params.type == 'add'"
        v-auth="'shop.admin.coupon.add'"
        type="primary"
        @click="confirm"
        >保存</el-button
      >
      <el-button
        v-if="modal.params.type == 'edit'"
        v-auth="'shop.admin.coupon.edit'"
        type="primary"
        @click="confirm"
        >更新</el-button
      >
    </el-footer>
  </el-container>
</template>
<script setup>
  import { onMounted, reactive, ref, unref } from 'vue';
  import { isEmpty, cloneDeep } from 'lodash';
  import { api } from './coupon.service';
  import { useModal } from '@/sheep/hooks';
  import GoodsSelect from '@/app/shop/admin/goods/goods/select.vue';
  import CategorySelect from '@/app/shop/admin/category/select.vue';
  import { ElMessage } from 'element-plus';

  const emit = defineEmits(['modalCallBack']);
  const props = defineProps(['modal']);

  const formRef = ref();
  const form = reactive({
    model: {
      name: '',
      type: 'reduce', // 优惠券类型:reduce=满减券,discount=折扣券
      use_scope: 'all_use', // 可用范围:all=全场通用,goods=指定商品可用,disabled_goods=指定商品不可用,category=指定分类可用
      items: '',
      items_value: [],
      amount: '',
      max_amount: '',
      enough: '',
      stock: '',
      limit_num: '',
      get_time: '',
      use_time_type: 'days',
      use_time: '',
      start_days: '',
      days: '',
      is_double_discount: '',
      description: '',
      status: 'normal', // 状态:normal=公开,hidden=后台发放,disabled=禁用
    },
    rules: {
      name: [{ required: true, message: '请填写券名称', trigger: 'blur' }],
      type: [{ required: true, message: '请选择券类型', trigger: 'blur' }],
      enough: [{ required: true, message: '请填写消费门槛', trigger: 'blur' }],
      amount: [{ required: true, message: '请填写使用面额', trigger: 'blur' }],
      max_amount: [{ required: true, message: '请填写最大优惠', trigger: 'blur' }],
      stock: [{ required: true, message: '请填写发券总量', trigger: 'blur' }],
      get_time: [{ required: true, message: '请选择优惠券发放时间', trigger: 'blur' }],
      use_time: [{ required: true, message: '请选择优惠券可使用时间', trigger: 'blur' }],
      use_time_type: [{ required: true, message: '请选择优惠券使用时间类型', trigger: 'blur' }],
      days: [{ required: true, message: '请填写优惠券有效天数', trigger: 'blur' }],
      use_scope: [{ required: true, message: '请选择可用范围', trigger: 'blur' }],
    },
  });

  async function getDetail() {
    const { error, data } = await api.detail(props.modal.params.id);
    if (error === 0) {
      form.model = data;
      form.model.get_time = [data.get_start_time, data.get_end_time];
      if (data.use_time_type == 'days') {
        form.model.use_time = '';
      } else if (data.use_time_type == 'range') {
        form.model.use_time = [data.use_start_time, data.use_end_time];
      }
    }
  }

  function selectGoods() {
    let ids = [];
    form.model.items_value.forEach((i) => {
      ids.push(i.id);
    });
    useModal(
      GoodsSelect,
      {
        title: '选择商品',
        multiple: true,
        ids,
      },
      {
        confirm: (res) => {
          form.model.items_value = res.data;
        },
      },
    );
  }

  function selectCategory() {
    let ids = [];
    form.model.items_value.forEach((i) => {
      ids.push(i.id);
    });
    useModal(
      CategorySelect,
      {
        title: '选择商品',
        multiple: true,
        from: 'coupon',
        ids,
      },
      {
        confirm: (res) => {
          form.model.items_value = [];
          form.model.items_value.push(...res.data.list);
        },
      },
    );
  }

  function deleteItems(index) {
    form.model.items_value.splice(index, 1);
  }

  function changeUseScope() {
    form.model.items_value = [];
  }

  function confirm() {
    unref(formRef).validate(async (valid) => {
      if (!valid) return;
      let submitForm = cloneDeep(form.model);
      if (Number(submitForm.enough) < Number(submitForm.amount)) {
        ElMessage({
          message: '请输入正确的使用门槛',
          type: 'warning',
        });
        return;
      }
      if (
        submitForm.use_scope == 'goods' ||
        submitForm.use_scope == 'disabled_goods' ||
        submitForm.use_scope == 'category'
      ) {
        let ids = [];
        submitForm.items_value.forEach((i) => {
          ids.push(i.id);
        });
        submitForm.items = ids.join(',');
      } else if (submitForm.use_scope == 'all_use') {
        submitForm.items = '';
      }
      delete submitForm.items_value;

      if (!isEmpty(submitForm.use_time)) {
        submitForm.use_time = submitForm.use_time.join(' - ');
      }

      if (!isEmpty(submitForm.get_time)) {
        submitForm.get_time = submitForm.get_time.join(' - ');
      }

      const res =
        props.modal.params.type == 'add'
          ? await api.add(submitForm)
          : await api.edit(props.modal.params.id, submitForm);
      if (res.error == 0) {
        emit('modalCallBack', {
          event: 'confirm',
          data: {
            uuID: props.modal.params.uuID,
          },
        });
      }
    });
  }

  onMounted(() => {
    if (props.modal.params.type == 'edit') {
      getDetail();
    }
  });
</script>
<style lang="scss" scoped>
  .el-range-editor.el-input__inner {
    // width: 360px;
  }
  .sa-template-wrap {
    // width: 360px;
    .key {
      flex: none;
      width: 400px;
    }
    .oper {
      flex: none;
      width: 60px;
    }
    .item {
      border-bottom: 1px solid var(--sa-space);
      & > .el-form-item {
        margin-bottom: 12px;
      }
      .goods {
        height: 16px;
        line-height: 16px;
        font-size: 12px;
        .goods-title {
          color: var(--sa-font);
        }
        .goods-price {
          color: var(--el-color-danger);
        }
        .goods-stock {
          color: var(--sa-font);
        }
      }
    }
    &.sa-template-wrap-activity {
      width: 464px;
    }
  }
  //Switch开启颜色
  .openswitch {
    color: var(--el-color-primary);
  }
  .get-time {
    max-width: 500px;
  }
  .warning-title {
    color: #faad14;
    font-size: 12px;
    line-height: 16px;
  }
</style>
